<?php 
/**
* 
*/
class Code
{
	public $config=[
		'width'=>200,//背景宽
		'height'=>100,//背景高
		'str'=>'1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM',//验证码字符
		'fontSize'=>40,//验证码字体大小
		'fontFile'=>'./White.ttf',//验证码字体文件路径
		'codeAngle'=>[-15,15],//验证码字体偏移角度
		'length'=>4,//验证码个数
		'ganrao'=>true,//是否要干扰符合
		'codeColor'=>[[0,255],[0,100],[0,100]],//验证码颜色范围
		'bgColor'=>[[200,255],[200,255],[200,255]],//背景颜色范围
	];
	public $src;
	public $code=[];
	public function __construct($config=[])
	{
		$this->config = array_merge($this->config,$config);
		$this->entry();
	}

	public function __get($name){
		return $this->config[$name];
	}

	public function entry(){
		$this->createCanvas();//创建画布
		$this->createCode();//生成验证码
		if ($this->ganrao) {
			$this->ganrao();//产生干扰
		}
		header("Content-type: image/png");
		imagepng($this->src);
	}
	//创建画布
	public function createCanvas(){
		$this->src = imagecreatetruecolor($this->width, $this->height);
		$color = $this->mtRandColor($this->bgColor[0],$this->bgColor[1],$this->bgColor[2]);
		$color = imagecolorallocate($this->src, $color[0], $color[1], $color[2]);
		imagefill($this->src, 0, 0, $color);
	}
	//生成验证码
	private function createCode(){
		for($i=0;$i<$this->length;$i++){
			$color=$this->mtRandColor($this->codeColor[0],$this->codeColor[1],$this->codeColor[2]);
			$color = imagecolorallocate($this->src, $color[0], $color[1], $color[2]);
			$str=$this->str[mt_rand(0,strlen($this->str)-1)];
			$this->fontSize = $this->fontSize > 0.6*$this->height ? 0.6*$this->height : $this->fontSize;
			$x=($i==0)?($this->width-($this->length*$this->fontSize))/($this->length+1):$i*($this->fontSize+($this->width-($this->length*$this->fontSize))/($this->length+1));
			$y=($this->height+$this->fontSize)/2;
			imagettftext($this->src, $this->fontSize, mt_rand($this->codeAngle[0],$this->codeAngle[1]), $x, $y, $color, $this->fontFile, $str);
			$this->code[$i]=$str;
		}
	}
	//产生随机颜色
	public function mtRandColor($red=[0,255],$green=[0,255],$blue=[0,255]){
		$color = [mt_rand($red[0],$red[1]),mt_rand($green[0],$green[1]),mt_rand($blue[0],$blue[1])];
		return $color;
	}

	//产生干扰
	private function ganrao(){
		$n=ceil($this->length*10);
		for($i=0;$i<$n;$i++){
			$str=$this->str[mt_rand(0,strlen($this->str)-1)];
			$color=$this->mtRandColor($red=[150,200],$green=[150,200],$blue=[150,200]);
			$color = imagecolorallocate($this->src, $color[0], $color[1], $color[2]);
			imagettftext ( $this->src, 20 , mt_rand(-15,15) , mt_rand(0,$this->width) , mt_rand(0,$this->height) , $color , './White.ttf' , $str);
		}
	}
}



$code = new code();
// $code->entry();
// var_dump($code->code);

?>